package com.yociyy.gen.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.yociyy.common.constants.Constants;
import com.yociyy.gen.config.GenConfig;
import com.yociyy.gen.entity.GenColumn;
import com.yociyy.gen.entity.GenTable;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器工具类
 *
 * @author: YoCiyy
 * @date: 2020/5/19
 */
public class GenUtils {

	/**
	 * 获取代码生成模板
	 *
	 * @return 模板列表
	 */
	public static List<String> getTemplates() {
		List<String> vm = new ArrayList<String>();
		// 后端代码模板
		vm.add("vm/java/controller.java.vm");
		vm.add("vm/java/biz.java.vm");
		vm.add("vm/java/entity.java.vm");
		vm.add("vm/java/mapper.java.vm");
		vm.add("vm/mapper/mapper.xml.vm");
//		// 前端代码模板
		vm.add("vm/vue/api.js.vm");
		vm.add("vm/vue/table.vue.vm");
		vm.add("vm/vue/modal.vue.vm");
//		// sql 模板
		vm.add("vm/sql/sql.vm");
		return vm;
	}

	/**
	 * 生成代码
	 *
	 * @param table 表信息
	 * @param columns 列信息
	 * @param zip 流
	 */
	public static void genCode(GenTable table, List<GenColumn> columns, ZipOutputStream zip) {

		// 表信息
		// 移除表前缀，转换为java类名
		if (StrUtil.isNotBlank(GenConfig.getTablePrefix())) {
			String tableName = table.getTableName().replace(GenConfig.getTablePrefix(), "");
			table.setClassName(columnToJava(tableName));
		}

		// 列信息
		for (GenColumn column : columns) {
			// 列名转换为java属性名
			column.setAttrName(StringUtils.uncapitalize(columnToJava(column.getColumnName())));
			// 列类型转换为java类型
			String attrType = GenConfig.getColumnType().containsKey(column.getDataType()) ? String.valueOf(GenConfig.getColumnType().get(column.getDataType())) : "unknowType";
			column.setAttrType(attrType);
			// 是否主键
			if ("PRI".equalsIgnoreCase(column.getColumnKey())) {
				table.setPk(column);
			}
		}
		table.setColumns(columns);

		// 没主键，则第一个字段为主键
		if (ObjectUtil.isNull(table.getPk())) {
			table.setPk(columns.get(0));
		}

		// 设置velocity资源加载器
		initVelocity();

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tableName", table.getTableName());
		map.put("tableComment", table.getTableComment());
		map.put("pk", table.getPk());
		map.put("ClassName", table.getClassName());
		map.put("className", StringUtils.uncapitalize(table.getClassName()));
		map.put("columns", table.getColumns());
		map.put("packageName", GenConfig.getPackageName());
		map.put("author", GenConfig.getAuthor());
		map.put("moduleName", GenConfig.getModuleName());
		map.put("businessName", GenConfig.getBusinessName());
		map.put("functionName", GenConfig.getFunctionName());
		map.put("methodName", WordUtils.capitalize(GenConfig.getBusinessName()));
		map.put("datetime", DateUtil.format(new Date(), "yyyy-MM-dd"));

		VelocityContext context = new VelocityContext(map);

		// 获取模板列表
		List<String> templates = getTemplates();
		for (String template : templates) {
			// 渲染模板
			StringWriter sw = new StringWriter();
			Template tpl = Velocity.getTemplate(template, "UTF-8");
			tpl.merge(context, sw);
			try {
				// 添加到zip
				zip.putNextEntry(new ZipEntry(getFileName(template, table.getClassName(), GenConfig.getPackageName(), GenConfig.getModuleName())));
				IOUtils.write(sw.toString(), zip, "UTF-8");
				IOUtils.closeQuietly(sw);
				zip.closeEntry();
			} catch (IOException e) {
				throw new RuntimeException("渲染模板失败，表名：" + table.getTableName(), e);
			}
		}
	}

	/**
	 * 列名转换成Java属性名
	 * 
	 * @param columnName 列名
	 * @return 转换后java属性名
	 */
	public static String columnToJava(String columnName) {
		return WordUtils.capitalizeFully(columnName, new char[] { '_' }).replace("_", "");
	}

	/**
	 * 初始化 velocity模板
	 */
	public static void initVelocity() {
		Properties prop = new Properties();
		prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		prop.setProperty(Velocity.OUTPUT_ENCODING, Constants.UTF8);
		prop.setProperty(Velocity.ENCODING_DEFAULT, Constants.UTF8);
		Velocity.init(prop);
	}

	/**
	 * 获取文件名
	 */
	public static String getFileName(String template, String className, String packageName, String moduleName) {
		String packagePath = "main" + File.separator + "java" + File.separator;
		String frontPath = "ui" + File.separator;

		if (StrUtil.isNotBlank(packageName)) {
			packagePath += packageName.replace(".", File.separator) + File.separator;
		}

		// 后端模板
		if (template.contains("biz.java.vm")) {
			return /*packagePath + "biz" + File.separator +*/ className + "Biz.java";
		} else if (template.contains("mapper.java.vm")) {
			return /*packagePath + "mapper" + File.separator +*/ className + "Mapper.java";
		} else if (template.contains("entity.java.vm")) {
			return /*packagePath + "entity" + File.separator +*/ className + ".java";
		} else if (template.contains("controller.java.vm")) {
			return /*packagePath + "controller" + File.separator +*/ className + "Controller.java";
		} else if (template.contains("mapper.xml.vm")) {
			return /*"main" + File.separator + "resources" + File.separator + "mapper" + File.separator +*/ className + "Mapper.xml";
		} else if (template.contains("sql.vm")) {
			return className + ".sql";
		} else if (template.contains("api.js.vm")) {
			return /*frontPath + "api" + File.separator + moduleName + File.separator + toLowerCaseFirstOne(className) + File.separator +*/ "api.js";
		} else if (template.contains("modal.vue.vm")) {
			return /*frontPath + "api" + File.separator + moduleName + File.separator + toLowerCaseFirstOne(className) + File.separator +*/ className + "Modal.vue";
		} else if (template.contains("table.vue.vm")) {
			return /*frontPath + "views" + File.separator + moduleName + File.separator + toLowerCaseFirstOne(className) + File.separator +*/ className + "Table.vue";
		}
		return null;
	}

	// 首字母转小写
	public static String toLowerCaseFirstOne(String s) {
		if (Character.isLowerCase(s.charAt(0))) {
			return s;
		} else {
			return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
		}
	}
}
